package leetcode.每日一题;

import org.junit.Test;

import java.util.*;

/**
 * @author ：zsy
 * @date ：Created 2022/9/26 11:05 AM
 * @description：
 */
public class 拆炸弹 {

    @Test
    public void test() {
        Solution solution = new Solution();
        System.out.println(Arrays.toString(solution.decrypt(new int[]{2,4,9,3}, -2)));
    }

    /**
     *
     * 3 9 4 2
     * 18, 16, 12, 3
     * k > 0   (i + k) % len
     *
     */
    class Solution {
        public int[] decrypt(int[] code, int k) {
            if (code.length == 0) return code;
            int len = code.length;
            int[] ans = new int[len];
            if (k == 0) return ans;
            List<Integer> list = new ArrayList<>();
            int sum = 0;
            for (int i = 0; i < code.length; i++) {
                list.add(code[i]);
                sum += code[i];
            }
            int n = k;
            if (k < 0) {
                Collections.reverse(list);
                n = -k;
            }
            for (int i = 1; i < list.size(); i++) {
                list.set(i, list.get(i) + list.get(i - 1));
            }

            for (int i = 0; i < len; i++) {
                int endIdx = (i + n) % len;
                int endSum = list.get(endIdx);
                if (endIdx <= i) {
                    endSum += sum;
                }
                int startSum = list.get(i);
                if (k < 0) {
                    ans[len - 1 - i] = endSum - startSum;
                } else {
                    ans[i] = endSum - startSum;
                }
            }
            return ans;
        }
    }

    /*class Solution {
        public int[] decrypt(int[] code, int k) {
            int n = code.length;
            if (k == 0) {
                return new int[n];
            }
            int[] res = new int[n];
            int[] newCode = new int[n * 2];
            System.arraycopy(code, 0, newCode, 0, n);
            System.arraycopy(code, 0, newCode, n, n);
            code = newCode;
            int l = k > 0 ? 1 : n + k;
            int r = k > 0 ? k : n - 1;
            int w = 0;
            for (int i = l; i <= r; i++) {
                w += code[i];
            }
            for (int i = 0; i < n; i++) {
                res[i] = w;
                w -= code[l];
                w += code[r + 1];
                l++;
                r++;
            }
            return res;
        }
    }*/

}
